package com.example.juc.controller;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @author jl
 * @since 2021/10/10 13:17
 */
class BankAccount {
    private String name = "ccb";
    public volatile int money;
    AtomicIntegerFieldUpdater fieldUpdater = AtomicIntegerFieldUpdater.newUpdater(BankAccount.class, "money");

    BankAccount() {
    }

    public void transfer(BankAccount bankAccount) {
        fieldUpdater.incrementAndGet(bankAccount);
    }

    public AtomicInteger balance = new AtomicInteger(0);
}

public class AtomicIntegerFieldUpdaterDemo {
    public static void main(String[] args) throws InterruptedException {
        BankAccount bankAccount = new BankAccount();
        int count = 100;
        CountDownLatch countDownLatch = new CountDownLatch(count);
        for (int i = 0; i < count; i++) {
            new Thread(() -> {
                try {
                    bankAccount.transfer(bankAccount);
                    bankAccount.balance.incrementAndGet();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }
            }).start();
        }
        countDownLatch.await();
        System.out.println("bankAccount.money = " + bankAccount.money);
        System.out.println("bankAccount.balance.get() = " + bankAccount.balance.get());
    }
}
